package com.zrx.service.impl;

import com.google.gson.Gson;
import com.mysql.cj.xdevapi.UpdateStatement;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zrx.domain.ResponseResult;
import com.zrx.enums.AppHttpCodeEnum;
import com.zrx.exception.SystemException;
import com.zrx.service.UploadService;
import com.zrx.utils.PathUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 *
 * @author 张荣欣
 * @create ：2022/9/20  16:50
 */
@Service
@Data
@ConfigurationProperties(prefix = "oss")
public class UploadServiceImpl implements UploadService {


    private   String accessKey ;
    private   String secretKey ;
    private   String bucket ;


    /**
     * 头像上传
     * @return
     */
    @Override
    public ResponseResult uploadImg(MultipartFile img) {
        // 判断文件类型或者文件大小
//        获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原文件名进行判断
        if (!originalFilename.endsWith(".png") && !originalFilename.endsWith(".jpg") ){
                throw  new SystemException(AppHttpCodeEnum.FILE_TYPR_ERROR);
        }
        //判断通过 上传文件到oss
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url =  uplpadOss(img,filePath);//2022/9/22****.png
        return ResponseResult.okResult(url);
    }

    private String uplpadOss(MultipartFile img, String filePath){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
//        String accessKey = "9ATwzIzwmWCOgjz7MZUT5e5gub6n_5QaXDel_boI";
//        String secretKey = "L3ML5tt5eEHMHoPSsMCyq_y_m2vz0vJeE31epboN";
//        String bucket = "zrx-blog";
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);


            InputStream inputStream = img.getInputStream();

            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://rihyqex90.hb-bkt.clouddn.com/"+key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "www";

    }
}

